package routers

import (
	"net/http"
	"punch/dbs"
	"punch/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

func LoadManager(e *gin.Engine) {
	e.POST("/punc/manager/add", managerAddHandler)
	e.POST("/punc/manager/delete", managerDeleteHandler)
	e.POST("/punc/manager/edit", managerEditHandler)
	e.POST("/punc/manager/get", managerGetHandler)
}

// 定义数据表
type Manager struct {
	Id          int    `db:"id"`
	Name        string `db:"name"`
	Account     string `db:"account"`
	Password    string `db:"password"`
	Create_time string `db:"create_time"`
	Update_time string `db:"update_time"`
}

type ManagerParamsAdd struct {
	Name    string `json:"name" binding:"required"`
	Account string `json:"account" binding:"required"`
}

type ManagerParamsDelete struct {
	Id int `json:"id" bingding:"required"`
}

type ManagerParamsEdit struct {
	Id       int    `json:"id" binding:"required"`
	Name     string `json:"name" binding:"required"`
	Account  string `json:"account" binding:"required"`
	Password string `json:"password"`
}

type ManagerParamsGet struct {
	PageNo   int    `json:"pageNo"`
	PageSize int    `json:"pageSize"`
	Id       int    `json:"id"`
	Name     string `json:"name"`
	Account  string `json:"account"`
}

func managerAddHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}

	var params ManagerParamsAdd
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	var manager []Manager
	err = db.Select(&manager, "select id from manager where account=?", params.Account)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}
	if len(manager) != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20010,
			"msg":  "已存在该用户",
		})
		return
	}

	r, err := db.Exec("insert into manager(name, account, password) values(?, ?, ?)",
		params.Name, params.Account, utils.GetMD5(utils.DEFAULT_PASSWORD))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}
	id, err := r.LastInsertId()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  err.Error(),
		})
		return
	}

	err = db.Select(&manager, "select * from manager where id=?", id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  err.Error(),
		})
		return
	}
	if len(manager) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20056,
			"msg":  "添加失败",
			"data": gin.H{
				"Id": id,
			},
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "添加成功",
		"data": gin.H{
			"Id":          id,
			"Account":     manager[0].Account,
			"Name":        manager[0].Name,
			"Create_time": manager[0].Create_time,
			"Update_time": manager[0].Update_time,
		},
	})
	db.Close()
}

func managerDeleteHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}
	var params ManagerParamsDelete
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	_, err = db.Exec("delete from manager where id=?", params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "删除成功",
		"data": gin.H{
			"Id": params.Id,
		},
	})

	db.Close()
}

func managerEditHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}

	var params ManagerParamsEdit
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	if tempID, _ := c.Get("UserID"); params.Id != tempID.(int) {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	var manager []Manager
	err = db.Select(&manager, "select * from manager where id=?", params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20023,
			"msg":  err.Error(),
		})
		return
	}
	if len(manager) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20030,
			"msg":  "没有此管理员",
			"data": gin.H{
				"Id": params.Id,
			},
		})
		return
	}

	manager[0].Name = params.Name
	manager[0].Account = params.Account
	if params.Password != "" {
		manager[0].Password = utils.GetMD5(params.Password)
	}

	_, err = db.Exec("update manager set name=?, account=?, password=? where id=?",
		manager[0].Name, manager[0].Account, manager[0].Password, params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20025,
			"msg":  err.Error(),
		})
		return
	}

	var manager2 []Manager
	err = db.Select(&manager2, "select name, account, create_time, update_time from manager where id=?", params.Id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20023,
			"msg":  err.Error(),
		})
		return
	}

	if len(manager2) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 20025,
			"msg":  "没有此管理员",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "更新成功",
		"data": manager2[0],
	})

	db.Close()
}

func managerGetHandler(c *gin.Context) {
	if tempUserType, _ := c.Get("Usertype"); tempUserType != "manager" {
		c.JSON(http.StatusOK, gin.H{
			"code": 20020,
			"msg":  "权限不足",
		})
		return
	}

	var params ManagerParamsGet
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20003,
			"msg":  err.Error(),
		})
		return
	}

	db, err := dbs.Conn(c)
	if err != nil {
		db.Close()
		return
	}

	tempSql := "select id, name, account, create_time, update_time from manager"
	hasAnd := " where"
	if params.Id != 0 {
		tempSql = tempSql + hasAnd + " id=" + strconv.Itoa(params.Id)
		hasAnd = " and"
	}
	if params.Name != "" {
		tempSql = tempSql + hasAnd + " name like '%" + params.Name + "%'"
		hasAnd = " and"
	}
	if params.Account != "" {
		tempSql = tempSql + hasAnd + " account like '%" + params.Account + "%'"
		hasAnd = " and"
	}
	tempSql = tempSql + " order by create_time desc"
	if params.PageNo != 0 && params.PageSize != 0 {
		tempSql = tempSql + " limit " + strconv.Itoa((params.PageNo-1)*params.PageSize) + "," + strconv.Itoa(params.PageSize)
	}

	var manager []Manager
	err = db.Select(&manager, tempSql)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 20004,
			"msg":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "查询成功",
		"data": manager,
	})

	db.Close()
}
